package com.caregiver.watch.common.utils.http;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;

import com.caregiver.watch.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

@Slf4j
public final class HttpUtils {

    private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();

    /**
     * GET请求
     *
     * @param url 请求的URL
     * @return 响应内容
     * @throws IOException
     */
    public static <T> T get(String url, Headers headers, TypeReference<T> resultType) throws IOException {
        log.info("接口调用开始！请求方法:{}", url);
        Request request = new Request.Builder()
                .headers(headers)
                .url(url)
                .build();
        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseJson = response.body().string();
            log.info("接口调用成功！请求方法:{},响应内容:{}", url, responseJson);
            return JSON.parseObject(responseJson, resultType);
        } catch (SocketTimeoutException e) {
            log.error("接口调用失败！请求方法:{},异常：{}", url, e.getMessage());
            throw new BaseException("接口请求超时，请重试！");
        } catch (IOException e) {
            log.error("接口调用失败！请求方法:{},异常：{}", url, e.getMessage());
            throw new BaseException("接口调用失败！IO异常:" + e.getMessage());
        }
    }

    private static Headers getHeaders() {
        return Headers.of("Content-Type", "application/json; charset=utf-8");
    }

    public static <T> T post(String url, String json, TypeReference<T> resultType) throws IOException {
        return post(url, getHeaders(), json, resultType);
    }

    /**
     * POST请求
     *
     * @param url  请求的URL
     * @param json 请求体的JSON内容
     * @return 响应内容
     * @throws IOException
     */
    public static <T> T post(String url, Headers headers, String json, TypeReference<T> resultType) throws IOException {
        log.info("接口调用开始！请求方法:{},请求内容:{}", url, json);
        RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(body)
                .build();

        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseJson = response.body().string();
            log.info("接口调用成功！请求方法:{},响应内容:{}", url, responseJson);
            return JSON.parseObject(responseJson, resultType);
        }
    }
}
